#include "stdafx.h"
#include "JigsawDrag.h"
#include "SKEYRmtDlg.h"

IMPLEMENT_DYNAMIC(CJigsawDrag, CDialogEx)

CJigsawDrag::CJigsawDrag(CWnd* pParent /*=NULL*/)
	: CDialogEx(CCodeShow::IDD, pParent)
{
	m_visible = false; m_pParent = nullptr;
	hScrDC = CreateDC(L"DISPLAY", NULL, NULL, NULL);
	hMemDC = nullptr; hOldBitmap = nullptr; bmpW = bmpH = -1;
}

CJigsawDrag::~CJigsawDrag()
{
}

BEGIN_MESSAGE_MAP(CJigsawDrag, CDialogEx)
	ON_WM_PAINT()
END_MESSAGE_MAP()

BOOL CJigsawDrag::Create(CSKEYRmtDlg* pParentWnd)
{
	m_pParent = pParentWnd;
	BOOL bRet = CDialogEx::Create(CCodeShow::IDD, pParentWnd);
	CRect r, r1; GetClientRect(&r); GetWindowRect(&r1);
	edgeW = r1.Width() - r.Width();
	edgeH = r1.Height() - r.Height();
	return bRet;
}

void CJigsawDrag::Show(CPoint pScreen)
{
	intptr_t w = bmpW + edgeW, h = bmpH + edgeH;
	SetWindowPos(&wndTopMost, pScreen.x, pScreen.y, (int)w, (int)h, SWP_NOACTIVATE | SWP_SHOWWINDOW);
	m_visible = true;
}

void CJigsawDrag::Hide()
{
	ShowWindow(SW_HIDE); m_visible = false;
}

void CJigsawDrag::setCD(HBITMAP bmp)
{
	BITMAP bm; ::GetObject(bmp, sizeof(BITMAP), &bm); bmpW = bm.bmWidth; bmpH = bm.bmHeight;
	if (!hMemDC)
	{
		hMemDC = CreateCompatibleDC(hScrDC);
		hOldBitmap = (HBITMAP)SelectObject(hMemDC, bmp);
	}
	else
	{
		HBITMAP hOld = (HBITMAP)SelectObject(hMemDC, bmp);
		if (hOld) DeleteObject(hOld);
	}
}

void CJigsawDrag::OnPaint()
{
	CPaintDC dc(this);
	if (hMemDC)
		dc.BitBlt(0, 0, (int)bmpW, (int)bmpH, CDC::FromHandle(hMemDC), 0, 0, SRCCOPY);
}

BOOL CJigsawDrag::DestroyWindow()
{
	if (hMemDC)
	{
		HBITMAP bmp = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
		if (bmp) DeleteObject(bmp);
		DeleteDC(hMemDC); hMemDC = NULL;
	}
	if (hScrDC)
	{
		DeleteDC(hScrDC); hScrDC = NULL;
	}
	return CDialogEx::DestroyWindow();
}
